package com.iotstudio.embeddedcloudplatform.service.serviceImp;

import com.iotstudio.embeddedcloudplatform.POJO.DO.Permission;
import com.iotstudio.embeddedcloudplatform.POJO.DTO.AuthorizationInformationDTO;
import com.iotstudio.embeddedcloudplatform.dao.*;
import com.iotstudio.embeddedcloudplatform.enums.IdentifyTypeEnum;
import com.iotstudio.embeddedcloudplatform.enums.ResultEnum;
import com.iotstudio.embeddedcloudplatform.POJO.DO.User;
import com.iotstudio.embeddedcloudplatform.POJO.DO.UserAuth;
import com.iotstudio.embeddedcloudplatform.POJO.DO.UserRole;
import com.iotstudio.embeddedcloudplatform.POJO.VO.ResultVO;
import com.iotstudio.embeddedcloudplatform.exception.CommonException;
import com.iotstudio.embeddedcloudplatform.service.RoleService;
import com.iotstudio.embeddedcloudplatform.service.UserService;
import com.iotstudio.embeddedcloudplatform.shiro.token.StatelessAuthenticationToken;
import com.iotstudio.embeddedcloudplatform.util.KeyUtil;
import com.iotstudio.embeddedcloudplatform.util.TokenUtil;
import com.iotstudio.embeddedcloudplatform.util.web.CookieUtil;
import com.iotstudio.embeddedcloudplatform.util.web.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author BeFondOfTaro
 * Created at 17:41 2018/1/19
 */
@Service
@Transactional
@Slf4j
public class UserServiceImp implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserSonserMapper userSonserMapper;

    @Override
    public ResultVO register(User user, UserAuth userAuth, String roleId) {
        if (userMapper.getByUsername(user.getUsername())!=null){
            throw new CommonException(ResultEnum.DUPLICATE_USERNAME);
        }
        UserRole userRole = new UserRole();
        String id = KeyUtil.genUniqueKey();
        user.setId(id);
        userAuth.setId(id);
        userAuth.setUserId(user.getId());
        userRole.setId(id);
        userRole.setUserId(user.getId());
        userRole.setRoleId(roleId);
        userMapper.insert(user);
        userAuthMapper.insert(userAuth);
        userRoleMapper.insert(userRole);
        return ResultVOUtil.success();
    }


    @Override
    public ResultVO login(HttpServletResponse response,Integer identifyType, String identifier, String credential) {
        UserAuth userAuth = userAuthMapper.getUserAuthByIdentifyTypeAndIdentifierAndCredential(
                identifyType,identifier,credential
        );
        //登录成功
        if (userAuth != null){
            //生成token，客户端作为令牌使用
            StatelessAuthenticationToken statelessAuthenticationToken = new StatelessAuthenticationToken();
            String userId = userAuth.getUserId();
            redisTemplate.opsForValue().set("CURRENT_USER",userId);
            statelessAuthenticationToken.setUserId(userId);
            String token = tokenUtil.createDigest(statelessAuthenticationToken,credential);
            CookieUtil.addCookie(response,"userId",userId);
            //设置返回的数据
            AuthorizationInformationDTO authorizationInformationDTO = new AuthorizationInformationDTO();
            authorizationInformationDTO.setUserId(userId);
            authorizationInformationDTO.setToken(userId + "." + token);
            authorizationInformationDTO.setRoleList(roleService.listRoleByUserId(userId));
            authorizationInformationDTO.setPermissionList(permissionMapper.listByUserId(userId));

            return ResultVOUtil.success(authorizationInformationDTO);
        }
        //登录失败
        else {
            //如果采用用户名登录
            if (identifyType.equals(IdentifyTypeEnum.USERNAME.getCode())){
                throw new CommonException(ResultEnum.PASSWORD_INCORRECT);
            }
            //其他方式登录
            else {
                throw new CommonException(ResultEnum.LOGIN_FAILED);
            }
        }
    }

    @Override
    public ResultVO logout() {
        tokenUtil.deleteToken((String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal());
        return ResultVOUtil.success();
    }

    @Override
    public List<Permission> listPermissionByUserId(String userId) {
        return permissionMapper.listByUserId(userId);
    }

    @Override
    public void deleteUser(String userId) {
        if (userAuthMapper.deleteByUserId(userId) < 1
                || userRoleMapper.deleteByUserId(userId) < 1
                || userMapper.deleteByPrimaryKey(userId) < 1){
            throw new CommonException(ResultEnum.DELETE_FAILED);
        }

    }

    @Override
    public User editUser() {
        String userId=redisTemplate.opsForValue().get("CURRENT_USER");
        User user=userMapper.getByUserId(userId);
        return user;
    }

    @Override
    public List<String> getSensorId(String userId) {
        List<String> list = userSonserMapper.getSensorId(userId);
        return list;
    }
}
